package com.ybb.vue.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ybb.vue.common.R;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.OperationRecordsUtils;
import com.ybb.vue.domain.AlarmTypeEnum;
import com.ybb.vue.domain.dto.EpmAlarmRuleDto;
import com.ybb.vue.entity.EpmAlarmRule;
import com.ybb.vue.entity.SysUser;
import com.ybb.vue.mapper.SysUserMapper;
import com.ybb.vue.service.EpmAlarmRuleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ybb
 * @version 1.0
 * @Description TODO
 * @Date 2023/3/22 15:51
 */

@RestController
@RequestMapping("/alarmRule")
public class EpmAlarmRuleController {

    @Autowired
    private EpmAlarmRuleService epmAlarmRuleService;

    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 查询alarmt列表
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping("/alarmRuleList")
    @PreAuthorize("hasAuthority('alarm:management:list')"+"||"+"hasAuthority('alarm:management:tquery')")
    public Result<?> alarmRuleList (@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                   @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<EpmAlarmRule> queryWrapper = Wrappers.<EpmAlarmRule>lambdaQuery();
        queryWrapper.like(EpmAlarmRule::getAlarmName, search);
        queryWrapper.orderByDesc(EpmAlarmRule::getUpdateTime);
        Page<EpmAlarmRule> result = epmAlarmRuleService.page(new Page<>(pageNum, pageSize),queryWrapper );
        List<EpmAlarmRule> alarmRuleList = result.getRecords();
        alarmRuleList.forEach(alarmRule -> {
            // 告警类型转译
            alarmRule.setAlarmTypeCode(AlarmTypeEnum.getAlarmType(alarmRule.getAlarmType()));

        });
        return Result.success(result);
    }

    /**
     * 添加
     * @param epmAlarmRuleDto
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('alarm:management:tadd')")
    public Result<?> save(@RequestBody @Valid EpmAlarmRuleDto epmAlarmRuleDto){
        return epmAlarmRuleService.save(epmAlarmRuleDto);
    }

    /**
     * 更新status状态
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/updateStatus/{id}/status/{status}")
    @PreAuthorize("hasAuthority('alarm:management:tedit')")
    public R updateStatus(@PathVariable(value = "id")String id, @PathVariable(value = "status")String status){
        EpmAlarmRule epmAlarmRule = epmAlarmRuleService.getById(id);
        epmAlarmRule.setStatus(status);
        // 编辑人
        epmAlarmRule.setEditor(SecurityContextHolder.getContext().getAuthentication().getName());
        epmAlarmRuleService.saveOrUpdate(epmAlarmRule);

        // 操作记录
        String content = "操作了告警规则表，【编辑规则状态】，记录id为：" + id;
        OperationRecordsUtils.createOperationRecords(content);
        return R.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping()
    @PreAuthorize("hasAuthority('alarm:management:tdelete')")
    public R delete(Long id){
        epmAlarmRuleService.removeById(id);

        // 操作记录
        String content = "操作了告警规则表，【删除】了1条记录，记录id为：" + id;
        OperationRecordsUtils.createOperationRecords(content);
        return R.ok();
    }

    /**
     * 修改
     * @param epmAlarmRuleDto
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('alarm:management:tedit')")
    public Result<?> update(@RequestBody @Valid EpmAlarmRuleDto epmAlarmRuleDto){
        EpmAlarmRule insert = new EpmAlarmRule();
        BeanUtils.copyProperties(epmAlarmRuleDto,insert);
        // 编辑人
        insert.setEditor(SecurityContextHolder.getContext().getAuthentication().getName());
        // 根据通知对象 写入对应的邮箱地址
        String[] notices = insert.getNoticeObject().split(",");
        List<String> noticeList = new ArrayList<String>(Arrays.asList(notices));
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda().in(SysUser::getUsername, noticeList));
        String emails = userList.stream().map(r -> r.getEmail()).collect(Collectors.joining(","));
        insert.setEmail(emails);

        // 操作记录
        String content = "操作了告警规则表，【修改】了1条记录，记录id为：" + epmAlarmRuleDto.getId();
        OperationRecordsUtils.createOperationRecords(content);
        return Result.success(epmAlarmRuleService.updateById(insert));
    }
}
